import domtoimage from 'dom-to-image-more'
/**
 * html dom 转 Base64 相关参数，同domtoimage.toPng
 */
export interface Dom2Base64Option {
  filter?: (node: Element) => boolean
  [someAttr: string]: any
}
/**
 * html dom 转 Base64
 * @group 功能: image操作相关
 */
export function dom2Base64(dom: HTMLDivElement, options?: Dom2Base64Option) {
  return domtoimage.toPng(dom, { ...options }) as Promise<string>
}

/**
 * 图片对象 转 Base64编码
 * @group 功能: image操作相关
 */
export function image2Base64(img: HTMLImageElement) {
  const canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  const ctx = canvas.getContext('2d')
  ctx?.drawImage(img, 0, 0, img.width, img.height)
  const dataURL = canvas.toDataURL('image/png')
  return dataURL
}

/**
 * 根据路径获取图片Base64编码
 * @group 功能: image操作相关
 */
export function getImgBase64(src: string) {
  return new Promise<string>((resolve, reject) => {
    let base64 = ''
    const img = new Image()
    img.src = src
    img.onload = function () {
      base64 = image2Base64(img)
      resolve(base64)
    }
  })
}

/**
 * 合并两张图片
 * @group 功能: image操作相关
 */
export function mergeImage(
  base64First: string,
  base64Next: string,
  width: number,
  height: number,
) {
  return new Promise<string>((resolve, reject) => {
    const canvas = document.createElement('canvas')
    canvas.width = width
    canvas.height = height
    const ctx = canvas.getContext('2d')

    const image = new Image() // MAP图片
    image.crossOrigin = 'Anonymous' // 支持跨域图片
    image.onload = () => {
      ctx?.drawImage(image, 0, 0, width, height)

      const image2 = new Image() // div图片
      image2.crossOrigin = 'Anonymous' // 支持跨域图片
      image2.onload = () => {
        ctx?.drawImage(image2, 0, 0, width, height)
        // 合并后的图片
        const base64 = canvas.toDataURL('image/png')
        resolve(base64)
      }
      image2.src = base64Next
    }
    image.src = base64First
  })
}
